<template>
	<view class="count-down-time">
		<view class="info-tip" v-if="infoTip">
			<view class="info">
				{{infoTip}} 
			</view>
			 
			
			<text v-if="isLesson"> 任课老师：{{ lessonObj.teacher }} 科目：{{lessonObj.subject}}</text>
		</view>
		
		<u-count-down v-if="isCountDown" :time="timeData" format="HH:mm:ss"  :finish="onFinish" ref="countDown" :autoStart="true">
		</u-count-down>
	</view>
</template>

<script>
	import { fetchData } from '../../utils/request';
	import timeFun from '../../utils/timeFunction.js'
	export default {
		name:"countDownTime",
		data() {
			return {
				 timeData: 0,
				 infoTip:'',
				 lessonObj:{
					 teacher:'', //上课老师
					 subject:''  // 科目
				 },
				 isCountDown:false,  // 下课中, 正在倒计时
				 isLesson:false, // 是否正在上课
				 timer:null
				 
			};
		},
		  methods: { 
		
			   onFinish(){
					this.timer = setInterval(()=>{
						this.calcCurTime();
					},1000*6)
					
			   },
			async getAllCourse(){
				this.timeList = [];
				let res = await fetchData({
				        url:'/database/feacourse/api/sClassCourseT',
				        method:'POST'
				    })
				const { feaCourseTDetailEntities} = res.data;
				      this.courseList = feaCourseTDetailEntities;
					  this.calcCurTime()
			},
	
			calcCurTime(){
				let totalNum = 0;
				
				this.isCountDown = false;
				this.infoTip = '';
				// 过滤当前的所有课程
				let today = new Date();
				let week =  today.getDay();    // [1,2,3,4,5,6,0]  周一到周日
				let objWeek = {
					  1:'mon',
					  2:'Tue',
					  3:'wed',
					  4:'thurs',
					  5:'fri',
					  6:'sat',
					  0:'sun'
				}	  
				let todayLeeson = this.courseList.filter((item)=>{
					 return item.week == objWeek[week]
				})
				
				// 课程按照时间排序 ， 从早到晚
				todayLeeson.sort((prev,next)=>{
					return Number(prev.feaCourseTSection.sTime.replace(/:/,'')) - Number(next.feaCourseTSection.sTime.replace(/:/,''));
				})
				let lenLesson = todayLeeson.length;
				
				for(let i=0;i<lenLesson;i++) {
				  const {sTime,eTime} = todayLeeson[i].feaCourseTSection;
				   // 判断是否正在上课
				  this.isLesson =  timeFun.checkAuditTime(sTime,eTime);
				  if(this.isLesson) {
					  this.lessonObj.subject = todayLeeson[i].subject;
					  this.lessonObj.teacher = todayLeeson[i].pNoTeacher;
					  
					 this.infoTip = '正在上课';
					 break; // 退出循环
				  }
				  
				 let timeCount = timeFun.getBeforeTime(sTime);
				  if(timeCount) {
					  this.timeData = timeCount;
					  this.isCountDown = true;
					  this.$nextTick(()=>{
						this.$refs.countDown.start();
					  })
					  break; // 退出循环
				  }
				   // 判断课程是否结束
				  let isFinish = timeFun.isAfterTime(eTime)
				   if(isFinish){
						totalNum+=1;					  
				   }
				}
				
				if(totalNum==lenLesson) {
					 // 课程已经结束
					 this.infoTip = '今天的课程已经结束'
				}
				
			},
			
		 },
		 mounted(){
			
			 this.getAllCourse();
		 }
	}
</script>

<style lang="scss" scoped>
	


</style>